/*
 * Copyright (c) 2020-2021, Bluetrum Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020/12/10     greedyhao    The first version
 */

/**
 * Notice!
 * All functions or data that are called during an interrupt need to be in RAM.
 * You can do it the way exception_isr() does.
 */
#define HAVE_DIR_STRUCTURE
#include <rtthread.h>
#include <stdio.h>
#include "board.h"
#include <ff.h>
#include <sys/statfs.h>
#include <dfs_fs.h>

#define LOG_TAG              "main"
#define LOG_LVL              LOG_LVL_INFO
#include <ulog.h>

#define RUN_MODE_EQ             0
#define RUN_MODE_NE             1
#define RUN_MODE_VALID_BEGIN    2
#define RUN_MODE_VALID_END      4
rt_sem_t uart1_rx_sem = RT_NULL;
rt_err_t uart1_rx_indicate_callback(rt_device_t uart, rt_size_t num) {
    if(uart1_rx_sem)
        rt_sem_release(uart1_rx_sem);
}
int uart_readline(rt_device_t uart, void *buf, rt_size_t size) {
    char *pbuf = buf;
    for(int n=0; n<size; ) {
        char c;
        if(rt_device_read(uart, -1, &c, 1) != 1) {
            rt_sem_take(uart1_rx_sem, RT_WAITING_FOREVER);
            continue;
        }
        if(c == '\r') {
            continue;
        } else {
            pbuf[n++] = c;
            if(c == '\n') {
                pbuf[n] = 0;
                return n;
            }
        }
    }
    return size;
}
/********************************************************************/
rt_device_t plogger_uart_init(const char *uart_name, int baud, int data_bits, int parity, int stop_bits) {
    // init uart.
    uart1_rx_sem = rt_sem_create("uart1_rx", 0, RT_IPC_FLAG_FIFO);
    RT_ASSERT(uart1_rx_sem != RT_NULL);
    rt_device_t uart = rt_device_find(uart_name);
    struct serial_configure serial_config = RT_SERIAL_CONFIG_DEFAULT;
    serial_config.baud_rate = baud;
    if(data_bits != -1)
        serial_config.data_bits = data_bits;
    if(parity != -1)
        serial_config.parity = parity;
    if(stop_bits != -1)
        serial_config.stop_bits = stop_bits;
    rt_err_t err = rt_device_control(uart, RT_DEVICE_CTRL_CONFIG, &serial_config);
    if(err != RT_EOK) {
        LOG_E("configure %s failed!\r\n", uart_name);
        RT_ASSERT(err != RT_EOK);
    }
    // open uart.
    err = rt_device_open(uart, RT_DEVICE_FLAG_INT_RX);
    if(err != RT_EOK) {
        LOG_E("open %s failed! %d\r\n", uart_name, err);
        RT_ASSERT(err != RT_EOK);
    }
    // set rx callback.
    rt_device_set_rx_indicate(uart, uart1_rx_indicate_callback);

    LOG_D("run. %p\r\n", uart);
    return uart;
}
bool plogger_check_sd() {
    int try_cnt = 3;
    rt_device_t sd_dev = RT_NULL;
    while((try_cnt-- > 0) && (sd_dev == RT_NULL)) {
        rt_thread_delay(rt_tick_from_millisecond(500));
        sd_dev = rt_device_find("sd0");
    }
    if(sd_dev == RT_NULL) {
        LOG_E("can't find sd0 device!");
        return false;
    }
    while(1) {
        struct statfs fs_info;
        int dfs_statfs(const char *path, struct statfs *buffer);
        if(!dfs_statfs("/", &fs_info)) {
            if(fs_info.f_blocks) {
                break;
            }
            LOG_E("Invalid block number.");
        }
        LOG_I("Wait until sdcard is valid.");
        rt_thread_delay(rt_tick_from_millisecond(1000));
    }
    return true;
}
bool plogger_copy_format_data(char **from, char **to) {
    char *pfrom = *from, *pto = *to;
    if(*pfrom != '[') {
        return false;
    }
    int i;
    for(i = 0; pfrom[i] && (pfrom[i] != ']'); i++) {}
    if(!pfrom[i]) {
        return false;
    }
    for(;*pfrom != ']';) {
        *pto++ = *pfrom++;
    }
    *pto++ = 0;
    *from = ++pfrom;
    *to = pto;
    return true;
}
char *plogger_get_next_string(char *buf, char split) {
    RT_ASSERT(buf != RT_NULL);
    for(;(*buf) && (*buf != split);buf++){}
    if(*buf) {
        return buf + 1;
    }
    return RT_NULL;
}
void plogger_replace_char(char *buf, char from, char to) {
    for( ;*buf; buf++){
        if(*buf == from) {
            *buf = to;
        }
    }
}
bool plogger_find_char(char *buf, char c, char split) {
    RT_ASSERT(buf != RT_NULL);
    for(;(*buf) && (*buf != split);buf++) {
        if(*buf == c) {
            return true;
        }
    }
    return false;
}
char **plogger_read_cmdline() {
    //%[=]\r\n[uart:]\r\nspi:\r\n
    //%[!]\r\ndebug:\r\n[info:]\r\n
    //%[!]s\r\nerror:\r\n[warning:]\r\n
    char **ret = RT_NULL;
    FIL fp;
    int tmp = f_open(&fp, "/cmdline.txt", FA_READ|FA_WRITE|FA_OPEN_ALWAYS);
    if(tmp == FR_OK) {
        char buf[128];
        rt_memset(buf, 0, sizeof(buf));
        f_read(&fp, buf, sizeof(buf) - 1, &tmp);
        f_close(&fp);
        //strcpy(buf, "%[!]s\r\nerror:\r\nwarning:");
        LOG_D("cmdline:%s\r\n", buf);
        if((buf[0] != '%') || (buf[1] != '[') || (buf[3] != ']')) {
            return RT_NULL;
        }
        int mode;
        if(buf[2] == '=') {
            mode = RUN_MODE_EQ;
        } else if(buf[2] == '!') {
            mode = RUN_MODE_NE;
        } else {
            return RT_NULL;
        }
        if(plogger_find_char(buf + 4, 's', '\n')) {
            mode |= RUN_MODE_VALID_BEGIN;
        }
        if(plogger_find_char(buf + 4, 'e', '\n')) {
            mode |= RUN_MODE_VALID_END;
        }
        //get first string
        char *head_buf = plogger_get_next_string(buf, '\n');
        LOG_D("head buf point: %d\r\n", (head_buf - buf));
        if(head_buf == RT_NULL)
            return RT_NULL;
        char *tmp_buf = head_buf;
        //get number of string.
        for(tmp = 0; tmp_buf; tmp++) {
            tmp_buf = plogger_get_next_string(tmp_buf, '\n');
        }
        LOG_D("fmt list number:%d", tmp);
        ret = rt_malloc(sizeof(char *) * (tmp + 2));
        if(ret) {
            char *next_str;
            tmp_buf = head_buf;
            int len;
            for(int i=0; i<tmp+2; i++) {
                ret[i] = RT_NULL;
            }
            ret[0] = (char *)mode;
            for(tmp = 1; tmp_buf; tmp++) {
                next_str = plogger_get_next_string(tmp_buf, '\n');
                if(next_str) {
                    len = (next_str - tmp_buf);
                } else {
                    len = rt_strlen(tmp_buf);
                }
                //empty line.
                if((len < 3) && (rt_strcmp(next_str-len, "\n") == 0)) {
                    break;
                }
                char *str = rt_malloc(len);
                if(!str) {
                    // malloc failed
                    break;
                }
                rt_memcpy(str, tmp_buf, len);
                plogger_replace_char(str, '\r', '\0');
                str[len] = 0;
                ret[tmp] = str;
                tmp_buf = next_str;
            }
        }
    } else {
        LOG_E("open cmdline.txt failed!%d, %d", tmp, rt_get_errno());
    }
    return ret;
}
bool plogger_is_ruled(char **rule_list, char *str) {
    RT_ASSERT(str != RT_NULL);
    if(rule_list == RT_NULL) {
        return true;
    }
    int mode = (int)rule_list[0];
    for(int i=1; rule_list[i]; i++) {
        //compare to begin or end
        if(mode&(RUN_MODE_VALID_BEGIN|RUN_MODE_VALID_END)){
            if(mode&RUN_MODE_VALID_BEGIN) {
                if(rt_strncmp(str, rule_list[i], rt_strlen(rule_list[i])) == 0) {
                    if(mode&0x01) {
                        return false;
                    }
                    return true;
                }
            }
            if(mode&RUN_MODE_VALID_END) {
                int str_len = rt_strlen(str);
                if(str[str_len - 1] == '\n') {
                    str_len - 1;
                }
                int rule_len = rt_strlen(rule_list[i]);
                if(rt_strncmp(str + str_len - rule_len, rule_list[i], rule_len) == 0) {
                    if(mode&0x01) {
                        return false;
                    }
                    return true;
                }
            }
        } else {
            //compare to substring.
            if(rt_strstr(str, rule_list[i])) {
                if(mode&0x01) {
                    return false;
                }
                return true;
            }
        }
    }
    if(mode&0x01) {
        return true;
    }
    return false;
}
bool plogger_read_config(int *baud, int *data_bits, int *parity, int *stop_bits, int *file_no) {
    RT_ASSERT(baud != RT_NULL);
    RT_ASSERT(data_bits != RT_NULL);
    RT_ASSERT(parity != RT_NULL);
    RT_ASSERT(stop_bits != RT_NULL);
    RT_ASSERT(file_no != RT_NULL);
    FIL fp;
    int tmp = f_open(&fp, "/config.txt", FA_READ|FA_WRITE|FA_OPEN_ALWAYS);
    if(tmp == FR_OK) {
        char buf[128];
        rt_memset(buf, 0, sizeof(buf));
        f_read(&fp, buf, sizeof(buf), &tmp);
        f_close(&fp);
        if(rt_strlen(buf) > 0) {
            sscanf(buf, "%d,%d%[NOE]%d%*[^0-9]%d", baud, data_bits, parity, stop_bits, file_no);
        } else {
            *baud = 9600;
            *data_bits = DATA_BITS_8;
            *parity = PARITY_NONE;
            *stop_bits = STOP_BITS_1;
            *file_no = 0;
        }
        if(*baud == 0) {
            *baud = 9600;
        }
        //*baud = 115200;
        int dataBits;
        switch(*data_bits) {
        case 5:
            *data_bits = DATA_BITS_5;
            dataBits = 5;
            break;
        case 6:
            *data_bits = DATA_BITS_6;
            dataBits = 6;
            break;
        case 7:
            *data_bits = DATA_BITS_7;
            dataBits = 7;
            break;
        case 9:
            *data_bits = DATA_BITS_9;
            dataBits = 9;
            break;
        default:
            *data_bits = DATA_BITS_8;
            dataBits = 8;
            break;
        }
        char parity_c;
        switch(*parity) {
        case 'O':
            *parity = PARITY_ODD;
            parity_c = 'O';
            break;
        case 'E':
            *parity = PARITY_EVEN;
            parity_c = 'E';
            break;
        default:
            *parity = PARITY_NONE;
            parity_c = 'N';
            break;
        }
        int stopBits;
        switch(*stop_bits) {
        case '2':
            *stop_bits = STOP_BITS_2;
            stopBits = 2;
            break;
        case '3':
            *stop_bits = STOP_BITS_3;
            stopBits = 3;
            break;
        case '4':
            *stop_bits = STOP_BITS_4;
            stopBits = 4;
            break;
        default:
            *stop_bits = STOP_BITS_1;
            stopBits = 1;
            break;
        }
        sprintf(buf, "%d,%d%C%d,file_no=%d\r\n", *baud, dataBits, parity_c, stopBits, (*file_no) + 1);
        tmp = f_open(&fp, "/config.txt", FA_READ|FA_WRITE|FA_CREATE_ALWAYS);
        if(tmp == FR_OK) {
            f_write(&fp, buf, rt_strlen(buf), &tmp);
            f_close(&fp);
        }
    } else {
        LOG_E("open config.txt failed!%d,%d", tmp);
        return false;
    }
    return true;
}
rt_sem_t sdcard_rw_sem = RT_NULL;
void plogger_log_init(void) {
    sdcard_rw_sem = rt_sem_create("sdcard_rw", 1, RT_IPC_FLAG_FIFO);
    RT_ASSERT(sdcard_rw_sem != RT_NULL);
}
bool plogger_log_file_open(FIL *fp, char *path) {
    //rt_sem_take(sdcard_rw_sem, RT_WAITING_FOREVER);
    int res = f_open(fp, path, FA_READ|FA_WRITE|FA_OPEN_APPEND);
    if(res != FR_OK) {
        //rt_sem_release(sdcard_rw_sem);
        LOG_E("open %s failed!", path);
        return false;
    }
    return true;
}
bool plogger_log_file_close(FIL *fp) {
    f_close(fp);
    //rt_sem_release(sdcard_rw_sem);
    return true;
}
bool plogger_save_to_file(FIL *fp, char *str) {
    int res;
    f_write(fp, str, rt_strlen(str), &res);
    if(res != FR_OK) {
        return false;
    }
    f_sync(fp);
    return true;
}
/********************************************************************/
static char str_buf[512];
#define USB_KEY_PIN         "PF1"
#define USE_RINGBUF         0
#if USE_RINGBUF
void rb_init();
int rb_write(uint8_t *buf, int size);
int rb_read(uint8_t *buf, int size);
int uart_rb_readline(rt_device_t uart, void *buf, rt_size_t size) {
    char *pbuf = buf;
    for(int n=0; n<size; ) {
        char c;
        if(rb_read(&c, 1) != 1) {
            rt_thread_delay(1);
            continue;
        }
        if(c == '\r') {
            continue;
        } else {
            pbuf[n++] = c;
            if(c == '\n') {
                pbuf[n] = 0;
                return n;
            }
        }
    }
    return size;
}
void task_uart_read(void *param) {
    rt_device_t uart = (rt_device_t)param;
    while(1) {
        char c;
        if(rt_device_read(uart, -1, &c, 1) != 1) {
            rt_sem_take(uart1_rx_sem, RT_WAITING_FOREVER);
            continue;
        }
        rb_write(&c, 1);
    }
}
#endif
int main(void)
{
    LOG_I("sysclk:%dKHz", get_sysclk_nhz()/1000);
    RT_ASSERT(plogger_check_sd());

    //cmdline
    char **fmt_list = plogger_read_cmdline();
    if (fmt_list) {
        rt_kprintf("fmt list(%d):\n", (int)fmt_list[0]);
        for(int i=1; fmt_list[i]; i++) {
            rt_kprintf("%d: %s\n", i-1, fmt_list[i]);
        }
        rt_kprintf("\n");
    } else {
        LOG_I("fmt list empty.\n");
    }
    //config
    int baud, data_bits, parity, stop_bits, file_no;
    char file_name[16];
    if(plogger_read_config(&baud, &data_bits, &parity, &stop_bits, &file_no)) {
        LOG_I("%d,%d-%d-%d,%d", baud, data_bits, parity, stop_bits, file_no);
    } else {
        LOG_E("read config failed! default:9600");
        baud = 9600;
        data_bits = -1;
        parity = -1;
        stop_bits = -1;
        file_no = 0;
    }
    sprintf(file_name, "log%08d.txt", file_no);
    // init sync sem.
    plogger_log_init();

    rt_device_t uart1 = plogger_uart_init("uart1", baud, data_bits, parity, stop_bits);
#if USE_RINGBUF
    rb_init();
    rt_thread_t tid = rt_thread_create("uart1_rx", task_uart_read, uart1, 1024, 9, 10);
    if(tid) {
        rt_thread_startup(tid);
    } else {
        rt_kprintf("tart uart1_rx task failed!\r\n");
    }
#endif
    FIL fp;
    bool file_ready;
    rt_memset((void *)&fp, 0, sizeof(fp));
    rt_pin_mode(rt_pin_get(USB_KEY_PIN), PIN_MODE_INPUT_PULLUP);
    if(rt_pin_read(rt_pin_get(USB_KEY_PIN))) { //release level is HIGH
        rt_kprintf("open %s ", file_name);
        file_ready = plogger_log_file_open(&fp, file_name);
        if(file_ready) {
            rt_kprintf("ok!\r\n");
        } else {
            rt_kprintf("failed!\r\n");
        }
    } else {
        file_ready = false;
        dfs_unmount("/");
        rt_kprintf("USB enabled!");
    }
    while (1) {
#if USE_RINGBUF
        int len = uart_rb_readline(uart1, str_buf, sizeof(str_buf) - 1);
#else
        int len = uart_readline(uart1, str_buf, sizeof(str_buf) - 1);
#endif
        if(len) {
            str_buf[len] = '\0';
            if(plogger_is_ruled(fmt_list, str_buf)) {
                if(file_ready) {
                    rt_tick_t cur_tick = rt_tick_get();
                    plogger_save_to_file(&fp, str_buf);
                    rt_kprintf("elapse: %d\r\n", rt_tick_get() - cur_tick);
                }
            } else {
                LOG_I("filter(%d):%s", len, str_buf);
            }
        }
    }
}

/*******************************************************/
#if USE_RINGBUF
#define RINGBUF_BUF_MAX         0x400
#define RINGBUF_BUF_MAX_MASK    0x3FF
static int rb_index_rd, rb_index_wr;
static uint8_t rb_buf[RINGBUF_BUF_MAX];
rt_sem_t rb_lock = NULL;
void rb_init() {
    rb_index_rd = rb_index_wr = 0;
    rb_lock = rt_sem_create("rb_lock", 1, RT_IPC_FLAG_FIFO);
    assert(rb_lock != RT_NULL);
}
int rb_write(uint8_t *buf, int size) {
    assert(buf != RT_NULL);
    rt_sem_take(rb_lock, RT_WAITING_FOREVER);
    if(size + rb_index_wr - rb_index_rd > RINGBUF_BUF_MAX) {
        size = RINGBUF_BUF_MAX - rb_index_wr + rb_index_rd;
    }
    if(size) {
        int off = rb_index_wr & RINGBUF_BUF_MAX_MASK;
        if(off + size >= RINGBUF_BUF_MAX) {
            int len = RINGBUF_BUF_MAX - off;
            rt_memcpy(rb_buf + off, buf, len);
            rt_memcpy(rb_buf, buf + off, size - len);
        } else {
            rt_memcpy(rb_buf + off, buf, size);
        }
        rb_index_wr += size;
    }
    rt_sem_release(rb_lock);
    return size;
}
int rb_read(uint8_t *buf, int size) {
    assert(buf != RT_NULL);
    rt_sem_take(rb_lock, RT_WAITING_FOREVER);
    if(rb_index_wr < size + rb_index_rd) {
        size = rb_index_wr - rb_index_rd;
    }
    if(size) {
        int off = rb_index_rd & RINGBUF_BUF_MAX_MASK;
        if(off + size >= RINGBUF_BUF_MAX) {
            int len = RINGBUF_BUF_MAX - off;
            rt_memcpy(buf, rb_buf + off, len);
            rt_memcpy(buf + off, rb_buf, size - len);
        } else {
            rt_memcpy(buf, rb_buf + off, size);
        }
        rb_index_rd += size;
    }
    rt_sem_release(rb_lock);
    return size;
}
#endif
